﻿#include <iostream>
#include <WinSock2.h>
#include <WS2tcpip.h>
#include <string>
#include <random>
#include <ctime>

#pragma comment(lib, "version.lib")

#include <windows.h>
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <memory>
#include "CrashHandler.hpp"


#include "util/net/smtp_transport.h"
#include "util/misc/zip.h"
#include "util/misc/unzip.h"

void CreateAndAddToZip() {
    // 创建 ZIP 文件
    HZIP hZip = CreateZip(L"D:\\123.zip", NULL);
    if (!hZip) {
        // 处理创建失败的情况
        std::cerr << "无法创建 ZIP 文件!" << std::endl;
        return;
    }

    // 添加文件到 ZIP
    ZRESULT result = ZipAdd(hZip,
        L"email.txt", L"E:\\Curl7.64.1\\x64\\bin\\email.txt");  // 只保存文件名，不包含路径

    if (result != ZR_OK) {
        // 处理添加失败的情况
        std::cerr << "添加文件失败，错误码: " << result << std::endl;
    }

    // 关闭 ZIP 文件
    CloseZip(hZip);
}




// Main initializeCrashpad function
bool initializeCrashpad() {

    CrashHandlerConfig config;
    config.handlerPath = "crashpad_handler.exe";
    config.reportsDir = "data";
    config.databasePath = "data";
    config.url = "smtp://smtp.qq.com:587";
    config.annotations = { {"version","1.0.0"}, {"product", "MyProduct"} , {"build_time", __TIME__},\
    {"extension_command","powershell.exe -Command \"Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser -Force; Start-Process powershell.exe -ArgumentList '-File ./crashpad/script.ps1' -NoNewWindow -Wait\""} };
    //config.arguments = { "--no-rate-limit","--capture-all-threads","--full-memory-dump"};
    config.arguments = { "--no-rate-limit"};
    config.restartable = true;
    config.asynchronous = false;

    config.mail = { "1078783119@qq.com" ,"ufqflbhvggudihef" ,"1078783119@qq.com" ,"1078783119@qq.com" ,"崩溃报告" ,u8"E:\\Curl7.64.1\\x64\\bin\\mx_crashpad_handler.pdb" };

    if (CrashHandler::Initialize(config)) {
        std::cout << "CrashHandler initialized successfully!" << std::endl;
    }
    else {
        std::cout << "Failed to initialize CrashHandler!" << std::endl;
        return false;
    }

    CrashHandler::SetLogFile(u8"D:\\图吧工具箱\\regid.2024-09_图吧工具箱.swidtag");

    return true;

    /*
    using base::FilePath;
    using crashpad::CrashpadClient;
    using crashpad::CrashReportDatabase;
    using crashpad::Settings;

    // Get application directory
    std::wstring base_path = GetExecutableDir() + L"\\..\\..\\..\\build_x64\\debug";
    std::wstring handler_path = base_path + L"\\crashpad_handler.exe";
    std::wstring data_path = base_path + L"\\data";

    // Construct the URL
    std::string url_path = ConstructUrl("example.com", "8088", "MyProduct");

    // Ensure that crashpad_handler exists
    FilePath handler(handler_path);

    // Save minidump data path
    FilePath reportsDir(data_path);

    // Disable rate limit to capture all crashes
    std::vector<std::string> arguments;
    arguments.push_back("--no-rate-limit");

    // Prepare annotations
    std::map<std::string, std::string> annotations;
    annotations["format"] = "minidump";
    annotations["version"] = "1.0.0";  // Replace with actual version
    annotations["product"] = "MyProduct";  // Replace with actual product name
    annotations["app_path"] = std::string(handler_path.begin(), handler_path.end());
    annotations["build_time"] = __TIME__;
    //annotations["extension_command"] = "notepad.exe";
    annotations["extension_command"] =
        "powershell.exe -Command \"Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser -Force; Start-Process powershell.exe -ArgumentList '-File script.ps1' -NoNewWindow -Wait\"";

    //annotations["extension_command"] = "powershell.exe -File script.ps1";
    // Initialize the local crash report database
    std::unique_ptr<CrashReportDatabase> database = CrashReportDatabase::Initialize(reportsDir);
    if (!database) {
        std::cerr << "Failed to initialize crash report database." << std::endl;
        return false;
    }

    // Configure settings for automatic uploads
    Settings* settings = database->GetSettings();
    if (!settings) {
        std::cerr << "Failed to get crash report database settings." << std::endl;
        return false;
    }
    settings->SetUploadsEnabled(false); // Toggle auto uploads

    // Initialize Crashpad
    CrashpadClient client;
    bool status = client.StartHandler(handler,
        reportsDir,
        reportsDir,
        "",
        annotations,
        arguments,
        true,
        true);

    if (!status) {
        std::cerr << "Failed to start crashpad handler." << std::endl;
    }
   
    return status;
     */
}
#include <thread>
#include "util/net/smtp_multipart_builder.h"
#include <base/strings/utf_string_conversions.h>

int main() {
    auto smtp = crashpad::SMTPTransport::Create();
    crashpad::SMTPMultipartBuilder smtp_multipart_builder;
    smtp_multipart_builder.SetGzipEnabled(true);
    smtp_multipart_builder.SetUserName("1078783119@qq.com");
    smtp_multipart_builder.SetPassWord("ufqflbhvggudihef");
    smtp_multipart_builder.SetSender("1078783119@qq.com");
    smtp_multipart_builder.AddRecipient("1078783119@qq.com");
    smtp_multipart_builder.SetSubject("崩溃报告");
    smtp_multipart_builder.SetFormData("version", "1.2.0.1");
    smtp_multipart_builder.AddFileAttachment(u8"E:\\Curl7.64.1\\x64\\bin\\email.txt");
    smtp_multipart_builder.AddFileAttachment(u8"E:\\Curl7.64.1\\x64\\bin\\mx_crashpad_handler.pdb");

    crashpad::SMTPAuthHeaders headers;
    smtp_multipart_builder.GetAuthHeaders(headers);
    smtp->SetAuthHeader(headers);
    smtp->SetBodyStream(smtp_multipart_builder.GetBodyStream());
    smtp->SetURL("smtp://smtp.qq.com:587");

    // 同步发送邮件
    std::string response;
    bool success = smtp->ExecuteSynchronously(&response);
    std::cout << (success ? "成功: " : "失败: ") << response << std::endl;

    return 0;

    /*
    auto smtp = crashpad::SMTPTransport::Create();

    // 配置SMTP服务器
    smtp->SetServer("smtp.qq.com", 587);
    smtp->SetCredentials("1078783119@qq.com", "ufqflbhvggudihef");
    smtp->SetSender("1078783119@qq.com");
    smtp->AddRecipient("1078783119@qq.com");
    smtp->SetSubject("崩溃报告");
    smtp->SetBody(u8"这是一个崩溃报告，请查收附件中的dump文件。");

    // 添加附件
    smtp->AddAttachment(u8"E:\\Curl7.64.1\\x64\\bin\\email.txt");
    //smtp->AddAttachment(u8"E:\\Curl7.64.1\\x64\\bin\\mx_crashpad_handler.pdb");
    //smtp->AddAttachment(u8"D:\\图吧工具箱\\regid.2024-09_图吧工具箱.swidtag");
    smtp->SetGzipEnabled(true);

    //smtp->AddAttachment("E:\\logs\\app.log");

    // 同步发送邮件
    std::string response;
    bool success = smtp->ExecuteSynchronously(&response);

    std::cout << (success ? "成功: " : "失败: ") << response << std::endl;

    return 0;
   
    initializeCrashpad();
	std::thread([]() {
		// Simulate some work in the thread
		std::this_thread::sleep_for(std::chrono::seconds(2));
        MessageBox(NULL, L"auto crash", L"crashpad", MB_OK);
		// Simulate a crash
		int* p = nullptr; // This will cause a crash (null pointer dereference)
		*p = 42; // Attempt to write to null pointer
        }).detach();
    MessageBox(NULL, L"wait for crash", L"crashpad", MB_OK);
      */
    return 0;
}

//---完整脚本--
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <windows.h>
#include <shellapi.h>
#include <shlobj.h>
#include <cstdio>
#include <cwchar>
#include <clocale>

// 获取环境变量
std::wstring GetEnvironmentVariable(const std::wstring& name) {
    wchar_t buffer[MAX_PATH];
    DWORD length = GetEnvironmentVariableW(name.c_str(), buffer, MAX_PATH);
    if (length == 0) {
        return L"";
    }
    return std::wstring(buffer, length);
}

// 分割字符串
std::vector<std::wstring> SplitString(const std::wstring& str, const std::wstring& delimiter) {
    std::vector<std::wstring> result;
    size_t pos = 0;
    std::wstring token;
    std::wstring s = str;

    while ((pos = s.find(delimiter)) != std::wstring::npos) {
        token = s.substr(0, pos);
        result.push_back(token);
        s.erase(0, pos + delimiter.length());
    }
    if (!s.empty()) {
        result.push_back(s);
    }
    return result;
}

// 获取当前时间戳字符串
std::wstring GetTimestamp() {
    SYSTEMTIME st;
    GetLocalTime(&st);

    wchar_t buffer[26];
    swprintf_s(buffer, L"%04d-%02d-%02d_%02d-%02d-%02d",
        st.wYear, st.wMonth, st.wDay,
        st.wHour, st.wMinute, st.wSecond);

    return std::wstring(buffer);
}

// 创建ZIP文件 (使用命令行工具替代COM接口)
bool CreateZipFile(const std::wstring& zipPath, const std::vector<std::wstring>& filePaths) {
    try {
        // 创建临时批处理文件
        std::wstring tempBatPath = GetEnvironmentVariable(L"TEMP") + L"\\create_zip.bat";
        std::wofstream batFile(tempBatPath);

        if (!batFile.is_open()) {
            std::wcerr << L"无法创建临时批处理文件" << std::endl;
            return false;
        }

        // 使用内置的压缩功能
        batFile << L"@echo off" << std::endl;
        batFile << L"setlocal" << std::endl;
        batFile << L"set zip=" << zipPath << std::endl;

        // 创建空ZIP文件
        batFile << L"fsutil file createnew \"%zip%\" 0" << std::endl;

        // 添加文件到ZIP
        for (const auto& filePath : filePaths) {
            batFile << L"powershell -Command \"Add-Type -AssemblyName System.IO.Compression.FileSystem; [System.IO.Compression.ZipFile]::Open('\"%zip%\"', 'Update').CreateEntryFromFile('\"" << filePath << L"\"', '\"" << std::wstring(filePath).substr(filePath.find_last_of(L"\\/") + 1) << L"\"')\"" << std::endl;
        }

        batFile << L"endlocal" << std::endl;
        batFile.close();

        // 执行批处理文件
        STARTUPINFOW si = { sizeof(si) };
        PROCESS_INFORMATION pi;
        wchar_t cmdLine[MAX_PATH] = { 0 };
        swprintf_s(cmdLine, L"\"%s\"", tempBatPath.c_str());

        if (!CreateProcessW(NULL, cmdLine, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi)) {
            std::wcerr << L"无法执行批处理文件: " << GetLastError() << std::endl;
            return false;
        }

        // 等待进程结束
        WaitForSingleObject(pi.hProcess, INFINITE);

        // 清理
        CloseHandle(pi.hProcess);
        CloseHandle(pi.hThread);
        DeleteFileW(tempBatPath.c_str());

        return true;
    }
    catch (const std::exception& e) {
        std::wcerr << L"创建ZIP文件时出错: " << e.what() << std::endl;
        return false;
    }
}

#include <windows.h>
#include <wininet.h>
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
#include <random>
#include <algorithm>
#include <cctype>

#pragma comment(lib, "wininet.lib")

template <typename T>
const T& _min(const T& a, const T& b) {
    return (a < b) ? a : b;
}

// Base64编码函数
std::string Base64Encode(const std::vector<BYTE>& data) {
    static const char* base64_chars =
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

    std::string encoded;
    encoded.reserve(((data.size() + 2) / 3) * 4);

    for (size_t i = 0; i < data.size(); i += 3) {
        DWORD b = (data[i] << 16);
        if (i + 1 < data.size()) b |= (data[i + 1] << 8);
        if (i + 2 < data.size()) b |= data[i + 2];

        encoded.push_back(base64_chars[(b >> 18) & 0x3F]);
        encoded.push_back(base64_chars[(b >> 12) & 0x3F]);

        if (i + 1 < data.size()) encoded.push_back(base64_chars[(b >> 6) & 0x3F]);
        else encoded.push_back('=');

        if (i + 2 < data.size()) encoded.push_back(base64_chars[b & 0x3F]);
        else encoded.push_back('=');
    }

    return encoded;
}

// 从文件读取所有字节
bool ReadFileBytes(const std::wstring& filePath, std::vector<BYTE>& bytes) {
    std::ifstream file(filePath, std::ios::binary | std::ios::ate);
    if (!file) return false;

    std::streamsize size = file.tellg();
    file.seekg(0, std::ios::beg);

    bytes.resize(size);
    if (!file.read(reinterpret_cast<char*>(bytes.data()), size)) {
        bytes.clear();
        return false;
    }

    return true;
}

// 转换宽字符串为多字节字符串(UTF-8)
std::string WideToUTF8(const std::wstring& wstr) {
    if (wstr.empty()) return "";

    int size_needed = WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), NULL, 0, NULL, NULL);
    std::string result(size_needed, 0);
    WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), &result[0], size_needed, NULL, NULL);
    return result;
}

// 生成随机MIME边界
std::string GenerateMimeBoundary() {
    static const char charset[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    const int length = 30;

    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> dis(0, sizeof(charset) - 2);

    std::string boundary = "---------------------------";
    boundary.reserve(boundary.size() + length);

    for (int i = 0; i < length; ++i) {
        boundary += charset[dis(gen)];
    }

    return boundary;
}

// 创建临时文件并写入内容
bool CreateTempFile(const std::string& content, std::wstring& filePath) {
    wchar_t tempPath[MAX_PATH];
    if (!GetTempPathW(MAX_PATH, tempPath)) {
        return false;
    }

    wchar_t tempFileName[MAX_PATH];
    if (!GetTempFileNameW(tempPath, L"mail", 0, tempFileName)) {
        return false;
    }

    filePath = tempFileName;

    std::ofstream file(filePath);
    if (!file) {
        return false;
    }

    file << content;
    file.close();

    return true;
}

// 使用CreateProcess执行命令并获取输出
bool ExecuteCommand(const std::wstring& command, std::wstring& output, DWORD& exitCode) {
    SECURITY_ATTRIBUTES saAttr;
    saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
    saAttr.bInheritHandle = TRUE;
    saAttr.lpSecurityDescriptor = NULL;

    // 创建匿名管道
    HANDLE hReadPipe, hWritePipe;
    if (!CreatePipe(&hReadPipe, &hWritePipe, &saAttr, 0)) {
        return false;
    }

    // 设置子进程信息
    STARTUPINFOW si;
    PROCESS_INFORMATION pi;

    ZeroMemory(&si, sizeof(si));
    si.cb = sizeof(si);
    si.hStdError = hWritePipe;
    si.hStdOutput = hWritePipe;
    si.dwFlags |= STARTF_USESTDHANDLES;

    ZeroMemory(&pi, sizeof(pi));

    // 创建子进程
    BOOL bSuccess = CreateProcessW(
        NULL,                   // 不指定可执行文件路径
        const_cast<LPWSTR>(command.c_str()), // 命令行参数
        NULL,                   // 进程安全属性
        NULL,                   // 线程安全属性
        TRUE,                   // 句柄可继承
        CREATE_NO_WINDOW,       // 创建无窗口进程
        NULL,                   // 不使用环境变量
        NULL,                   // 不使用当前目录
        &si,                    // 启动信息
        &pi                     // 进程信息
    );

    if (!bSuccess) {
        CloseHandle(hReadPipe);
        CloseHandle(hWritePipe);
        return false;
    }

    // 关闭写管道，以便读取输出
    CloseHandle(hWritePipe);

    // 读取进程输出
    const int bufferSize = 4096;
    wchar_t buffer[bufferSize];
    DWORD bytesRead;
    std::wstringstream outputStream;

    while (ReadFile(hReadPipe, buffer, bufferSize * sizeof(wchar_t), &bytesRead, NULL) && bytesRead > 0) {
        outputStream.write(buffer, bytesRead / sizeof(wchar_t));
    }

    output = outputStream.str();

    // 等待进程结束并获取退出代码
    WaitForSingleObject(pi.hProcess, INFINITE);
    GetExitCodeProcess(pi.hProcess, &exitCode);

    // 清理资源
    CloseHandle(hReadPipe);
    CloseHandle(pi.hProcess);
    CloseHandle(pi.hThread);

    return true;
}

bool SendEmail(const std::wstring& subject, const std::wstring& body, const std::wstring& attachmentPath) {
    // SMTP服务器配置
    const std::wstring smtpServer = L"smtp.qq.com";
    const int smtpPort = 587;
    const std::wstring username = L"1078783119@qq.com";
    const std::wstring password = L"ufqflbhvggudihef";
    const std::wstring recipient = L"1078783119@qq.com";

    // 转换为UTF-8
    std::string utf8Subject = WideToUTF8(subject);
    std::string utf8Body = WideToUTF8(body);

    // 生成MIME边界
    std::string boundary = GenerateMimeBoundary();

    // 构建邮件内容
    std::stringstream mailContent;
    mailContent << "From: " << WideToUTF8(username) << "\r\n";
    mailContent << "To: " << WideToUTF8(recipient) << "\r\n";
    mailContent << "Subject: " << utf8Subject << "\r\n";
    mailContent << "MIME-Version: 1.0\r\n";
    mailContent << "Content-Type: multipart/mixed; boundary=\"" << boundary << "\"\r\n\r\n";

    // 邮件正文
    mailContent << "--" << boundary << "\r\n";
    mailContent << "Content-Type: text/plain; charset=\"utf-8\"\r\n";
    mailContent << "Content-Transfer-Encoding: 8bit\r\n\r\n";
    mailContent << utf8Body << "\r\n\r\n";

    // 处理附件
    if (!attachmentPath.empty()) {
        // 提取文件名
        size_t lastSlash = attachmentPath.find_last_of(L"\\/");
        std::string fileName = lastSlash != std::wstring::npos
            ? WideToUTF8(attachmentPath.substr(lastSlash + 1))
            : WideToUTF8(attachmentPath);

        // 读取附件文件
        std::vector<BYTE> fileBytes;
        if (!ReadFileBytes(attachmentPath, fileBytes)) {
            std::wcerr << L"无法读取附件文件: " << attachmentPath << std::endl;
            return false;
        }

        // 进行Base64编码
        std::string base64Content = Base64Encode(fileBytes);

        // 添加附件部分到邮件内容
        mailContent << "--" << boundary << "\r\n";
        mailContent << "Content-Type: application/octet-stream\r\n";
        mailContent << "Content-Disposition: attachment; filename=\"" << fileName << "\"\r\n";
        mailContent << "Content-Transfer-Encoding: base64\r\n\r\n";

        // 按每行76个字符分割Base64内容（符合RFC 2045规范）
        for (size_t i = 0; i < base64Content.size(); i += 76) {
            mailContent << base64Content.substr(i, _min<size_t>(76ul, base64Content.size() - i)) << "\r\n";
        }
        mailContent << "\r\n";
    }

    // 结束边界
    mailContent << "--" << boundary << "--\r\n";

    // 创建临时文件存储邮件内容
    std::string mailData = mailContent.str();
    std::wstring mailFilePath;
    if (!CreateTempFile(mailData, mailFilePath)) {
        return false;
    }

    // 构建curl命令行
    std::wstringstream command;
    command << L"curl -v --url \"smtp://" << smtpServer << L":" << smtpPort << L"\" ";
    command << L"--ssl ";
    command << L"--mail-from \"<" << username << L">\" ";
    command << L"--mail-rcpt \"<" << recipient << L">\" ";
    command << L"--user \"" << username << L":" << password << L"\" ";
    command << L"--login-options \"AUTH=LOGIN\" ";
    command << L"--upload-file \"" << mailFilePath << L"\" ";

    // 执行curl命令
    std::wstring output;
    DWORD exitCode;
    bool success = ExecuteCommand(command.str(), output, exitCode);

    // 删除临时文件
    DeleteFileW(mailFilePath.c_str());

    // 检查执行结果
    if (!success || exitCode != 0) {
        std::wcerr << L"邮件发送失败，退出代码: " << exitCode << std::endl;
        std::wcerr << L"错误信息: " << output << std::endl;
        return false;
    }

    return true;
}


// 检查管理员权限
bool IsAdmin() {
    BOOL isAdmin = FALSE;
    SID_IDENTIFIER_AUTHORITY ntAuthority = SECURITY_NT_AUTHORITY;
    PSID adminGroup;

    if (AllocateAndInitializeSid(&ntAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID,
        DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &adminGroup)) {
        if (!CheckTokenMembership(NULL, adminGroup, &isAdmin)) {
            isAdmin = FALSE;
        }
        FreeSid(adminGroup);
    }

    return isAdmin != 0;
}

// 获取系统信息
std::wstring GetSystemInfo() {
    std::wstring info;

    // 计算机名称
    wchar_t computerName[MAX_COMPUTERNAME_LENGTH + 1];
    DWORD size = MAX_COMPUTERNAME_LENGTH + 1;
    if (GetComputerNameW(computerName, &size)) {
        info += L"计算机名称：" + std::wstring(computerName) + L"\n";
    }

    // 当前用户名
    wchar_t userName[MAX_PATH];
    size = MAX_PATH;
    if (GetUserNameW(userName, &size)) {
        info += L"当前用户名：" + std::wstring(userName) + L"\n";
    }

    // 管理员权限状态
    info += L"是否管理员权限：" + std::wstring(IsAdmin() ? L"是" : L"否") + L"\n";

    // 操作系统信息
    OSVERSIONINFOEXW osInfo = { 0 };
    osInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW);
    if (GetVersionExW(reinterpret_cast<LPOSVERSIONINFOW>(&osInfo))) {
        info += L"操作系统：Windows ";
        info += std::to_wstring(osInfo.dwMajorVersion) + L"." + std::to_wstring(osInfo.dwMinorVersion);
        info += L" 构建 " + std::to_wstring(osInfo.dwBuildNumber) + L"\n";
    }

    // CPU信息
    SYSTEM_INFO sysInfo;
    GetSystemInfo(&sysInfo);
    info += L"CPU 信息：";

    HKEY hKey;
    if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",
        0, KEY_QUERY_VALUE, &hKey) == ERROR_SUCCESS) {
        wchar_t cpuName[512];
        DWORD size = 512;
        if (RegQueryValueExW(hKey, L"ProcessorNameString", NULL, NULL,
            reinterpret_cast<LPBYTE>(cpuName), &size) == ERROR_SUCCESS) {
            info += cpuName;
        }
        RegCloseKey(hKey);
    }
    info += L"\n";

    // 内存信息
    MEMORYSTATUSEX memInfo;
    memInfo.dwLength = sizeof(MEMORYSTATUSEX);
    if (GlobalMemoryStatusEx(&memInfo)) {
        double totalMemory = static_cast<double>(memInfo.ullTotalPhys) / (1024 * 1024);
        double freeMemory = static_cast<double>(memInfo.ullAvailPhys) / (1024 * 1024);

        info += L"可用内存/总内存：" + std::to_wstring(static_cast<int>(freeMemory)) + L" MB / "
            + std::to_wstring(static_cast<int>(totalMemory)) + L" MB\n";
    }

    return info;
}

int main11() {
    // 设置locale以支持宽字符输出
    std::setlocale(LC_ALL, "");

    // 设置控制台输出为UTF-8
    //SetConsoleOutputCP(CP_UTF8);

    // 脚本开始的警告提示 - 全部使用wprintf替代std::wcout
    wprintf(L"魅熙的小伙伴 你好\n");
    wprintf(L"当你看到这个内容的时候说明 谷小微 已经发生了无法恢复的错误\n");
    wprintf(L"脚本将会自动打包相关错误文件发送至开发者邮箱中\n");
    wprintf(L"感谢理解\n");

    // 获取文件路径
    std::wstring dumpFilePaths;
    std::wstring logFilePaths;

#ifdef _DEBUG
    dumpFilePaths = L"59455b00-6542-413e-bc68-6e84f5f9ebd9.dmp";
    logFilePaths = L"WeChat-liujian371400.log";
#else
    // 从环境变量中读取 DUMPFILE_PATH 和 LOGFILE_PATH
    dumpFilePaths = GetEnvironmentVariable(L"DUMPFILE_PATH");
    logFilePaths = GetEnvironmentVariable(L"LOGFILE_PATH");
#endif

    std::vector<std::wstring> dumpPaths;
    if (!dumpFilePaths.empty()) {
        dumpPaths = SplitString(dumpFilePaths, L";");
    }
    else {
        fwprintf(stderr, L"环境变量 'DUMPFILE_PATH' 未设置或为空。\n");
    }

    std::vector<std::wstring> logPaths;
    if (!logFilePaths.empty()) {
        logPaths = SplitString(logFilePaths, L";");
    }
    else {
        fwprintf(stderr, L"环境变量 'LOGFILE_PATH' 未设置或为空。\n");
    }

    // 获取系统临时目录路径
    wchar_t tempPath[MAX_PATH];
    GetTempPathW(MAX_PATH, tempPath);
    std::wstring tempDir(tempPath);

    // 根据当前时间动态生成压缩文件路径
    std::wstring timestamp = GetTimestamp();
    std::wstring zipPath = tempDir + L"dump_files_" + timestamp + L".zip";

    wprintf(L"压缩包文件路径已设置为系统临时目录：%ls\n", zipPath.c_str());

    // 检查路径是否存在并打包
    std::vector<std::wstring> validPaths;
    wprintf(L"正在处理 DUMP 文件：\n");

    for (const auto& path : dumpPaths) {
        wprintf(L"  %ls\n", path.c_str());

        if (GetFileAttributesW(path.c_str()) != INVALID_FILE_ATTRIBUTES) {
            wprintf(L"  文件存在，已添加到压缩包……\n");
            validPaths.push_back(path);
        }
        else {
            fwprintf(stderr, L"  文件不存在：%ls\n", path.c_str());
        }
    }

    wprintf(L"正在处理 LOG 文件：\n");

    for (const auto& path : logPaths) {
        wprintf(L"  %ls\n", path.c_str());

        if (GetFileAttributesW(path.c_str()) != INVALID_FILE_ATTRIBUTES) {
            wprintf(L"  文件存在，已添加到压缩包……\n");
            validPaths.push_back(path);
        }
        else {
            fwprintf(stderr, L"  文件不存在：%ls\n", path.c_str());
        }
    }

    try {
        if (!validPaths.empty()) {
            // 如果ZIP文件已存在则删除
            if (GetFileAttributesW(zipPath.c_str()) != INVALID_FILE_ATTRIBUTES) {
                DeleteFileW(zipPath.c_str());
            }

            // 创建ZIP文件
            if (CreateZipFile(zipPath, validPaths)) {
                wprintf(L"文件已成功压缩到：%ls\n", zipPath.c_str());
            }
            else {
                fwprintf(stderr, L"创建压缩文件失败！\n");
                return 1;
            }

            // 准备发送邮件
            wprintf(L"开始发送邮件并附带压缩包……\n");

            // 获取当前计算机名称
            wchar_t computerName[MAX_COMPUTERNAME_LENGTH + 1];
            DWORD size = MAX_COMPUTERNAME_LENGTH + 1;
            GetComputerNameW(computerName, &size);

            // 获取系统信息
            std::wstring sysInfo = GetSystemInfo();

            // 动态生成邮件正文
            std::wstring body = L"您好，\n\n我们为您整理了当前计算机的详细信息：\n\n" + sysInfo +
                L"\n附件中包含相关的 DUMP 和 LOG 文件数据，请查收。\n\n此致，\n开发者";

            // 获取当前日期
            SYSTEMTIME st;
            GetLocalTime(&st);
            std::wstring dateStr = std::to_wstring(st.wMonth) + L"/" + std::to_wstring(st.wDay);

            // 邮件主题
            std::wstring subject = L"来自 " + std::wstring(computerName) + L" 计算机 的数据 - " + dateStr;

            // 发送邮件
            if (SendEmail(subject, body, zipPath)) {
                wprintf(L"邮件已成功发送！\n");
            }
            else {
                fwprintf(stderr, L"发送邮件失败！\n");
                return 1;
            }
        }
        else {
            fwprintf(stderr, L"未找到有效文件，脚本退出。\n");
            return 1;
        }
    }
    catch (const std::exception& e) {
        // 异常处理
        fwprintf(stderr, L"发生异常：\n");
        fwprintf(stderr, L"%S\n", e.what());
        wprintf(L"请查看以上错误信息，并按任意键继续……\n");
        std::cin.get();
        return 1;
    }

    // 删除压缩包文件
    try {
        if (GetFileAttributesW(zipPath.c_str()) != INVALID_FILE_ATTRIBUTES) {
            DeleteFileW(zipPath.c_str());
        }
    }
    catch (const std::exception& e) {
        fwprintf(stderr, L"无法删除临时文件: %S\n", e.what());
    }

    // 自动倒计时退出
    wprintf(L"灾难现场已经收集完毕 脚本将在 5 秒后退出……\n");
    Sleep(5000);

    return 0;
}